﻿using System;
using System.IO;
using UnityEditor;
using UnityEngine;

public class StringDrawType : BaseDrawType
{
    const string path = "path";
    public override Type type { get { return typeof(string); } }
    public override string Draw(string name, string arg)
    {
        if(name.ToLower() != path)
        {
            return EditorGUILayout.TextField(name,arg);

        }
        else
        {
            var rect =  EditorGUILayout.GetControlRect();
            arg = EditorGUI.TextField(rect,name, arg);
            if(rect.Contains(Event.current.mousePosition) && Event.current.type == EventType.DragUpdated)
            {
                DragAndDrop.visualMode = DragAndDropVisualMode.Copy;
            }
            if(Event.current.type == EventType.DragPerform && rect.Contains(Event.current.mousePosition))
            {
                DragAndDrop.AcceptDrag();
                if(DragAndDrop.paths.Length>0)
                {
                    var path = DragAndDrop.paths[0];
                    var index = path.IndexOf("Resources");
                    
                    AssetImporter importer = AssetImporter.GetAtPath(path);
                    if(Directory.Exists(path))
                    {
                        Debug.LogError("This is not a valid path");
                    }
                    else if(index!=-1)
                    {
                        var extension = Path.GetExtension(path);
                        arg = path.Substring(index + "Resources".Length + 1).Replace(extension,string.Empty);
                    }
                    else if(!string.IsNullOrEmpty(importer.assetBundleName))
                    {
                        arg = string.Format("{0}:{1}", importer.assetBundleName,Path.GetFileNameWithoutExtension(path));
                    }
                    else
                    {
                        Debug.LogError(string.Format("The {0} could not be loaded at runtime", DragAndDrop.objectReferences[0]));
                    }
                }
                Event.current.Use();
            }
            
            return arg;
        }
    }
}